package buber.genetic.op;

import buber.genetic.ChromosomeArray;
import buber.genetic.SimpleMember;
import buber.genetic.SimplePopulation;
import buber.genetic.interfaces.Chromosome;
import buber.genetic.interfaces.Member;
import buber.genetic.interfaces.Population;
import buber.genetic.op.interfaces.CrossOp;
import buber.util.MathUtils;

public class SimpleCrosser implements CrossOp {

	public Member cross(Member m1, Member m2) {
		int pos = MathUtils.random(m1.chSize());
		Member m = new SimpleMember();
		m=cross(m1,m2,pos);
		return m;
	}

	public Population doOperator(Population pop) {
		Population result = new SimplePopulation();
		Population tmp = pop.getClone();
		//System.out.println("[tmp]"+tmp.size());
		
		boolean done=false;
		while(!done){
			int g1=MathUtils.random(tmp.size());
			int g2=MathUtils.random(tmp.size());
			while(g2==g1){
				g2=MathUtils.random(tmp.size());
			}
			//System.out.print("[g1]="+g1);
			//System.out.print(" [g2]="+g2);
			//System.out.println(" [size]="+tmp.size());
			Member m1 = tmp.getMembers().get(g1);
			Member m2 = tmp.getMembers().get(g2);
			int pos = MathUtils.random(m1.chSize());
			Member newM1 = cross(m1,m2,pos);
			Member newM2 = cross(m2,m1,pos);
			result.addMember(newM1);
			result.addMember(newM2);
			if(g1>g2){
			tmp.getMembers().remove(g1);
			tmp.getMembers().remove(g2);
			}else{
				tmp.getMembers().remove(g2);
				tmp.getMembers().remove(g1);
				
			}
			if(tmp.size()<=1){
				done=true;
			}
		}
		return result;
	}
	private Member cross(Member m1,Member m2,int pos){
		Chromosome ch = new ChromosomeArray(m1.chSize());
		for(int i=0;i<pos;i++){
			ch.setGene(i, m1.getChromosomes().get(0).getGene(i));
		}
		for(int j=pos;j<m1.chSize();j++){
			ch.setGene(j, m2.getChromosomes().get(0).getGene(j));
			
		}
		Member m = new SimpleMember();
		m.getChromosomes().add(ch);
		return m;
	}
	
}
